/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

var lastSearch = 'local';

function glRender(value, p, record) {
	if (record.id=="-1") {
		return "<span class=\"glossary-header\">"+record.data.comments+"</span>";
	}
	return "<span class=\"glossary-header\">"+value+"</span>";
}

MyDesktop.Glossary = Ext.extend(Ext.app.Module, {
	id:'glossary-win',
	text: _('Glossary'),

    init : function(){
        this.launcher = {
            text: this.text,
            iconCls:'glossary',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(src){

        var desktop = this.app.getDesktop();
        var winname = "glossaryWin";
        var win = desktop.getWindow(winname);
		var tabPanel;
		var searchBox;
		
        if(!win){
			if (getPref("gSearchMode")!=null) {
				lastSearch = getPref("gSearchMode");
			}
			
			searchBox = new Verbum.SearchField({
				emptyText: _('Enter query press RETURN'),
				listeners: {submit: this.doSearch},
				minTextLength: 4
			});

		    tabPanel = new Ext.TabPanel({
		        activeTab: 0,
		        width:600,
		        height:250,
		        plain:true,
		        enableTabScroll: true,
		        defaults:{autoScroll: true},
		        tbar: new Ext.Toolbar({
					items:[ searchBox,' ',
		                {
						xtype: 'combo',
						editable: false,
						triggerAction: 'all',
					   	store: [['local',_('Local')],['opens',_('open-tran.eu')],['all',_('All')]],
					   	width: 120,
					   	value: lastSearch,
					   	listeners: {select: 
					   				function(combo,record,index) {
					   					lastSearch = record.data.value;
					   					setPref("gSearchMode",lastSearch);
					   				}
					   		}
		                },'-',
						{
							xtype:'button',
							tooltip: _('Refresh selected tab'),
							iconCls: "x-tbar-loading",
							handler: function() {
								tabPanel.getActiveTab().store.reload();	
							}
						},'->',this.addCreate()
					 ]
		        })
		    });

			searchBox.tabPanel = tabPanel;
			
			tabPanel.add(this.createSearchTab());
			tabPanel.add(this.createTab(_('All'),'ALL'));
			for (var i="A".charCodeAt(0);i<="Z".charCodeAt(0);i++) {
				var ch = String.fromCharCode(i);
				tabPanel.add(this.createTab(ch,ch));
			}

            win = desktop.createWindow({
				id: winname,
				title: this.text,
				closable:true,
				width:640,
				height:450,
				plain:true,
				layout: 'fit',
				iconCls: 'glossary',
				items: tabPanel
            });
        }
          
        win.show();
    },

	display : function(){
        this.createWindow();
	},

	doSearch: function(field,value) {
		var tab = Ext.getCmp('tabGlossary_SR');
		tab.store.baseParams['id']=value;
		tab.store.baseParams['mode']=lastSearch;
		tab.store.load();
		field.tabPanel.activate(tab);
	},
	
	loadData: function(tab) {
		if (!tab.loaded) {
			tab.store.load();
			tab.loaded = true;
		}
	},
	
	createSearchTab: function() {
		simpleTab = this.createTab(_('Search Results'),"SR");
		simpleTab.loaded = true;
		simpleTab.purgeListeners();
		simpleTab.store.baseParams['op']='search';
		this.addEdit(simpleTab);
		return simpleTab;
	},
	
	addCreate: function (winname) {
		return {}
	},
	
	addEdit: function(grid) {
	},
	
	createTab: function(ch,cmd) {

		var tabGrid = new Ext.grid.GridPanel({
			loadMask: {msg: _('Please wait...')},
			id: 'tabGlossary_'+cmd,
			listeners: {activate: this.loadData},
			title: ch,
			loaded: false,
	        store: new Ext.data.Store({
	        	autoLoad: false,
				reader: new Ext.data.JsonReader({
					root: 'results',
					id: 'id'
					},[
						{name: 'eterm', mapping: 'english_term'},
						{name: 'translationlist'},
						{name: 'related'},
						{name: 'comments'},
						{name: 'lastupdate'},
						{name: 'userid'},
				]),
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
				}),
				baseParams: {action: 'glossary', op: 'jump', id: cmd},
	        }),
	        columns: [
	            	{
	            		header: _('Term'),
	            		dataIndex: 'eterm',
	            		renderer: glRender,
	            		width: 230,
	            		sortable: true,
	            		hideable: false,
	            	},{
	            		header: _('Last Update on'), 
	            		dataIndex: 'lastupdate',
	            		sortable: true,
	            		renderer: renderUserDate,
	            	},{
	            		header: _('By'), 
	            		dataIndex: 'userid',
	            		sortable: true,
	            	}
	        ],
			view: new Ext.grid.GridView({
				forceFit:true,
        		enableRowBody:true,
        		getRowClass : function(record, rowIndex, p, store) {
            				var b = "<ul class=\"glossary-translation-body\">";
            				for (i=0;i<record.data.translationlist.length;i++) {
            					b += "<li class=\"glossary-translation-item\">"+record.data.translationlist[i]+"</li>";
            				}
            				b +="</ul>";
            				if (record.id!="-1") {
	            				b += "<br/>"+ String.format(_('<b>Reference: </b>{0}'),record.data.comments);
	            				b += "<br/>"+ String.format(_('<b>See also: </b><i>{0}</i>'),record.data.related);
            				}
            				p.body = b;
        				}
					}),
		    collapsible: true,
			animCollapse: false,
		});	
		
		this.addEdit(tabGrid);
		
		return tabGrid;
	}
});
